//
//  MYHomeController.m
//  MYChatting
//
//  Created by mac on 16/7/15.
//  Copyright © 2016年 lhf. All rights reserved.
//

#import "MYHomeController.h"
#import "VisitorLoginView.h"
#import "MYNetworkingTool.h"
#import "UserInfo.h"
#import "Status.h"
#import "User.h"
#import "MYStatusCell.h"
#import "MYRefreshControl.h"

@interface MYHomeController ()

//微博数组
@property (nonatomic,strong) NSMutableArray *statuses;

@property (nonatomic,strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic,weak) MYRefreshControl *refreshView;

@end

@implementation MYHomeController

static NSString *ID = @"MYCell";

- (void)viewDidLoad {
    [super viewDidLoad];
//   VisitorLoginView *v =  [[VisitorLoginView alloc] init];
//    [v setInfo:@"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知" andImageStr:nil];
//    self.view = v;
    UserInfo *userInfo = [[[UserInfo alloc] init] loadUserInfo];
    if ([userInfo.access_token length] <= 0) {
        [self.visitorLoginView setInfo:@"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知" andImageStr:nil];
        return;
    }else{
        [self loadStatus];
        
       // [self.tableView registerClass:[MYStatusCell class] forCellReuseIdentifier:ID];
        
        //预估行高
        self.tableView.estimatedRowHeight = 300;
        //设置自动计算行高
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
//        UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
//        [refreshControl addTarget:self action:@selector(refreshControlClick) forControlEvents:UIControlEventTouchUpInside ];
        MYRefreshControl *refreshView = [[MYRefreshControl alloc] init];
        self.refreshView = refreshView;
        [self.tableView addSubview:refreshView];
        [refreshView addTarget:self action:@selector(loadStatus) forControlEvents:UIControlEventValueChanged];
        
        self.tableView.tableFooterView = self.indicatorView;
    }
  
    
}





- (void)loadStatus{
    UserInfo *userInfo = [[[UserInfo alloc] init] loadUserInfo];
    int64_t max_id = 0;
    int64_t since_id = 0;
    //由于max_id since_id是互斥的，所以需要处理 使用if else语句即可
    if (self.indicatorView.isAnimating) {
        max_id = [self.statuses.lastObject id];
    }else{
        since_id = [self.statuses.firstObject id];
    }
    
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    [paramDict setObject:userInfo.access_token forKey:@"access_token"];
//    if (since_id > 0) {
//        [paramDict setObject:@(since_id) forKey:@"since_id"];
//    }
//    if (max_id > 0) {
//       [paramDict setObject:@(max_id) forKey:@"max_id"];
//    }
    [paramDict setObject:@(since_id) forKey:@"since_id"];
    [paramDict setObject:@(max_id) forKey:@"max_id"];
//    if (since_id > 0) {
//        [paramDict setObject:@(since_id) forKey:@"since_id"];
//    }
   // NSLog(@"---%f",[paramDict[@"since_id"] floatValue]);
    
    [[MYNetworkingTool sharedMYNetworkingTool]GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:paramDict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseDict = responseObject;
       // NSLog(@"???????%@",responseDict);
        NSArray *statuses = responseDict[@"statuses"];
       // NSLog(@"??????%ld",statuses.count);
        NSMutableArray *muArray = [NSMutableArray arrayWithCapacity:statuses.count];
        for (NSDictionary *statusDict in statuses) {
            Status *status = [Status statusWithDict:statusDict];
            [muArray addObject:status];
           // [self.statuses addObject:status];
        }
        //self.statuses = muArray;
    //    NSLog(@"muarray---%ld",muArray.count);
        //这样做的目的也是互斥的，因此使用if else
        if (since_id > 0) {
            self.statuses = [muArray arrayByAddingObjectsFromArray:self.statuses];
            [self.refreshView endRefreshing];
            NSLog(@"refsh---%ld",muArray.count);
        }else if (max_id > 0){
          [self.statuses addObjectsFromArray:muArray];
            
//            self.statuses = [self.statuses ];
            //数据加载完毕 动画停止
            [self.indicatorView stopAnimating];
        }else{
            self.statuses = muArray;
            
        }
        
#warning 一定要刷新，否则数据源方法中的数据是空的
        [self.tableView reloadData];
        
  
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}





#pragma 懒加载
- (NSMutableArray *)statuses{
    if (_statuses == nil) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}




#pragma 数据源方法
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     // NSLog(@"------%ld",self.statuses.count);
    return self.statuses.count;
  
}


- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    static NSString *ID = @"MYCell";
    //使用此方式，直接自定义cell了，不再关注cell的样式了 重要
    MYStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
  
    if (cell == nil) {
        cell = [[MYStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    Status *status = self.statuses[indexPath.row];
    cell.status = status;
    
    //判断加载数据   上拉加载更多数据 最后一行时
    if (!self.indicatorView.isAnimating && indexPath.row == self.statuses.count - 1) {
        [self.indicatorView startAnimating];
        
        //加载新数据
        [self loadStatus];
      //  NSLog(@"加载新数据");
    }
    return cell;
}


- (UIActivityIndicatorView *)indicatorView{
    if (_indicatorView == nil) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _indicatorView;
}

@end
